<template>
  <div class="cs-page-container">
    <div class="cs-filter-container">
      <el-select
        v-model="historyQuery.interval"
        clearable
        filterable
        placeholder="周期"
        style="width:100px"
      >
        <el-option label="1分钟" value="1" />
        <el-option label="5分钟" value="5" />
        <el-option label="10分钟" value="10" />
        <el-option label="30分钟" value="30" />
        <el-option label="60分钟" value="60" />
      </el-select>
      <el-date-picker
        v-model="historyDaterangeValue"
        :picker-options="daterangePickerOptions"
        type="datetimerange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="创建起始时间"
        end-placeholder="创建结束时间"
        value-format="yyyy/MM/dd HH:mm:ss"
        format="yyyy/MM/dd HH:mm:ss"
        :default-time="['00:00:00', '00:00:00']"
        @change="MydaterangeChanged"
      />
      <el-button
        type="primary"
        size="small"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        type="info"
        size="small"
        icon="el-icon-refresh-right"
        @click="resetFilter"
      >重置</el-button>
    </div>
    <LineChart :options="chartOptions" style="width:1500%;height:400px" />
    <div class="cs-filter-container">
      <el-input
        v-model.trim="listQuery.userId"
        clearable
        placeholder="请输入用户ID"
      />
      <el-select v-model="listQuery.chatType" filterable clearable placeholder="类型" style="width:90px">
        <el-option label="视频" :value="0"></el-option>
        <el-option label="语音" :value="1"></el-option>
      </el-select>
      <el-select v-model="listQuery.scene" clearable filterable placeholder="场景" style="width:100px">
        <el-option
          v-for="(item, i) in context_items"
          :key="i"
          :label="item"
          :value="i"
        />
      </el-select>
      <el-date-picker
        v-model="daterangeValue"
        :picker-options="daterangePickerOptions"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="起始时间"
        end-placeholder="结束时间"
        value-format="yyyy-MM-dd"
        clearable
        @change="daterangeChangedTimestamp"
      />
      <el-button
        type="primary"
        size="small"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        type="info"
        size="small"
        icon="el-icon-refresh-right"
        @click="resetFilter"
      >重置</el-button>
    </div>
    <div class="cs-filter-result">
      <el-table
        id="anchorListFirst"
        v-loading="listLoading"
        :data="list"
        :height="'calc(100vh - 330px)'"
        border
        fit
        size="small"
        highlight-current-row
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column align="center" label="发起者ID">
          <template slot-scope="{ row }">
            <TooptipsCom :user-id="row.fromUser" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="类型">
          <template slot-scope="{ row }">{{
            row.chatType === 0 ? '视频' : '语音'
          }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="场景">
          <template slot-scope="{ row }">{{
            context_items[row.context]
          }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="发起者性别">
          <template slot-scope="{ row }">{{ row.fromGender | gender }}</template>
        </el-table-column>
        <el-table-column align="center" label="发起者截图">
          <template slot-scope="{ row }">
            <image-tooltip :image-id="row.fromUrl">
              <img
                v-if="row.fromUrl"
                slot="img"
                :src="row.fromUrl + '?x-oss-process=image/resize,w_175'"
                style="cursor: pointer; width: 100px"
                title="点击放大"
                @click="zoomImage(row.fromUrl)"
              />
            </image-tooltip>

          </template>
        </el-table-column>
        <el-table-column align="center" label="发起者最大鉴黄分数" prop="fromRate">
        </el-table-column>
        <el-table-column align="center" label="接受者ID">
          <template slot-scope="{ row }">
            <TooptipsCom :user-id="row.toUser" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="接受者性别" prop="toGender">
          <template slot-scope="{ row }">{{ row.toGender | gender }}</template>
        </el-table-column>
        <el-table-column align="center" label="接受者截图">
          <template slot-scope="{ row }">
            <image-tooltip :image-id="row.toUrl">
              <img
                v-if="row.toUrl"
                slot="img"
                :src="row.toUrl + '?x-oss-process=image/resize,w_175'"
                style="cursor: pointer; width: 100px"
                title="点击放大"
                @click="zoomImage(row.toUrl)"
              />
            </image-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" label="接收者最大鉴黄分数" prop="toRate" />
        <el-table-column align="center" label="发起时间" prop="startTime">
          <template slot-scope="{ row }">{{ row.startTime | parseTime }}</template>
        </el-table-column>
        <el-table-column align="center" label="时长(分钟)">
          <template slot-scope="{ row }">
            {{ duration(row) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="消耗">
          <template slot-scope="{ row }">
            {{ consume(row) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="获得积分">
          <template slot-scope="{ row }">
            {{ row.pointGain }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="80"
        >
          <template slot-scope="{row}">
            <el-button
              v-if="row.chatType === 0"
              type="primary"
              size="mini"
              @click="onView(row.channelId)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <TablePagination
        :current-page="listQuery.page"
        :limit="listQuery.limit"
        :total="total"
        :loading="listLoading"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
      <ImageViewer :visible.sync="showImage" :url="imageUrl" />
    </div>
  </div>
</template>

<script>
import { xhrAnalysisRealHistory, xhrAnalysisRealTimeList } from '@/api/account'
import LineChart from '@/components/LineChart'
import TablePagination from '@/components/TablePagination';
import ImageViewer from '@/components/ImageViewer'
import { deepClone } from '@/utils';

export default {
  name: 'OnlineRealTime',
  components: { TablePagination, LineChart, ImageViewer },
  data() {
    return {
      historyQuery: {
        startTime: null,
        endTime: null,
        interval: null
      },
      showImage: false,
      imageUrl: null,
      historyDaterangeValue: '',
      chartOptions: {},
      daterangeValue: '',
      dialogLoading: false,
      listLoading: false,
      HistoryList: null,
      context_items: {
        1: '（花伴交友）IM内语音点播',
        2: '（花伴交友）IM内视频点播',
        3: '（花伴交友）缘分页面随机视频',
        4: '（花伴交友）缘分封面内语音点播',
        5: '（花伴交友）缘分封面内视频点播',
        6: '（花伴交友）详情页内语音点播',
        7: '（花伴交友）详情页内视频点播',
        8: '（花伴交友）随机语音匹配',
        9: '（花伴交友）随机视频匹配',
        10: '（花伴约会）IM内语音点播',
        11: '（花伴约会）IM内视频点播',
        12: '（花伴约会）随机语音匹配',
        13: '（花伴约会）随机视频匹配',
        14: '（花伴约会）封面内语音点播',
        15: '（花伴约会）封面内视频点播',
        16: '（花伴约会）详情页内语音点播',
        17: '（花伴约会）详情页内视频点',
        18: ' (花伴交友)音视频历史记录-语音点播',
        19: ' (花伴交友)音视频历史记录-视频点播',
        20: ' (花伴约会)音视频历史记录-语音点播',
        21: ' (花伴约会)音视频历史记录-视频点播'
      },
      total: 0,
      list: null,
      listQuery: {
        page: 1,
        limit: 100,
        startTime: null,
        endTime: null,
        userId: (this.$route.query && this.$route.query.id) || null
      }
    }
  },
  created() {
    this.doSearch()
  },
  methods: {
    doSearch: function() {
      xhrAnalysisRealTimeList(this.listQuery)
        .then(resp => {
          this.list = resp.data.list
          this.total = resp.data.count
          this.listLoading = false
        })
        .catch(err => {
          this.$message.error(err)
          this.listLoading = false
        })
      const historyQuery = deepClone(this.historyQuery)
      if (!historyQuery.interval) {
        historyQuery.interval = 5
      }
      const interval = (60 * 1000) * historyQuery.interval
      if (!historyQuery.endTime) {
        historyQuery.endTime = parseInt(new Date().getTime())
      }
      if (!historyQuery.startTime) {
        historyQuery.startTime = historyQuery.endTime - (1000 * 60 * 60 * 24);
      }
      xhrAnalysisRealHistory(historyQuery)
        .then(resp => {
          const historyData = {}
          for (const i in resp.data.list) {
            historyData[new Date(resp.data.list[i].dateTime).getTime()] = resp.data.list[i].callCount
          }
          const inventoryDate = []
          const series_data = []
          historyQuery.startTime = historyQuery.startTime - (historyQuery.startTime % interval);
          while (historyQuery.startTime < historyQuery.endTime) {
            const time = new Date(historyQuery.startTime);
            const y = time.getFullYear();
            const m = time.getMonth() + 1;
            const d = time.getDate();
            const h = time.getHours();
            const mm = time.getMinutes();
            const s = time.getSeconds();
            inventoryDate.push(y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) + ':' + this.add0(s))
            const callCount = historyData.hasOwnProperty(historyQuery.startTime) ? historyData[historyQuery.startTime] : 0
            series_data.push(callCount)
            historyQuery.startTime += interval
          }
          const series = {
              name: '通话数',
              type: 'line',
              data: series_data
          }
          this.drawLine(inventoryDate, series)
          this.listLoading = false
        })
        .catch(err => {
          this.$message.error(err)
          this.listLoading = false
        })
    },
    add0(m) { return m < 10 ? '0' + m : m },
    dataRefreh() {
      this.listLoading = true
      this.doSearch()
      this.$forceUpdate();
    },
    onView(channelId) {
      window.open(
        '/anchor/video-thumb-all?id=' + channelId
      )
    },
    duration(row) {
      if (row.acceptTime && row.endTime) {
        return ((row.endTime - row.acceptTime) / 60 / 1000).toFixed(2)
      }
      return '-'
    },
    consume(row) {
      const result = []
      if (row.tryCardCount) {
        result.push('试聊卡*' + row.tryCardCount)
      }
      if (row.diamondConsume) {
        result.push('钻石*' + row.diamondConsume)
      }
      if (row.videoCardCount) {
        result.push('视频卡*' + row.videoCardCount)
      }
      if (row.voiceCardCount) {
        result.push('语音卡*' + row.voiceCardCount)
      }
      return result.join(' ')
    },
    MydaterangeChanged() {
      if (this.historyDaterangeValue) {
        if (this.historyDaterangeValue[0]) {
          const startTime = this.historyDaterangeValue[0]
          this.historyQuery.startTime = /\d{2}:\d{2}$/g.test(startTime)
            ? new Date(startTime).getTime()
            : new Date(startTime + ' 00:00:00').getTime()
        }
        if (this.historyDaterangeValue[1]) {
          const endTime = this.historyDaterangeValue[1]
          this.historyQuery.endTime = /\d{2}:\d{2}$/g.test(endTime)
            ? new Date(endTime).getTime()
            : new Date(endTime + ' 23:59:59').getTime()
        }
      } else {
        this.historyQuery.startTime = null
        this.historyQuery.endTime = null
      }
    },
    drawLine(inventoryDate, series) {
      this.chartOptions = {
        title: {
          text: '历史通话'
        },
        legend: {
          data: ['通话数']
        },
        xAxisData: inventoryDate,
        series: series
      }
      this.this.$forceUpdate();
    },
    zoomImage(url) {
      this.showImage = true
      this.imageUrl = url
    }
  }
}
</script>

<style scoped>

</style>
